package me.leiusual.sharing.ui.product.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.ProductDetail
import timber.log.Timber

/**
 * author: leiusual
 * create on: 2019-07-27
 * description:
 */
class ProductOptionalAdapter(
    private val listener: ProductOptionalViewHolder.Listener
) : RecyclerView.Adapter<ProductOptionalViewHolder>() {

  private var dataSet = emptyList<ProductDetail.Option>()

  private var skus = emptyList<ProductDetail.Sku>()

  override fun getItemCount(): Int {
    return dataSet.size
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductOptionalViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val itemView = inflater.inflate(R.layout.view_holder_product_optional, parent, false)
    return ProductOptionalViewHolder(itemView, listener)
  }

  override fun onBindViewHolder(holder: ProductOptionalViewHolder, position: Int) {

    // 全部
    val allSkus = skus.map { it.sku }
    Timber.v("\n")
    Timber.v("allSkus = %s", allSkus)

    // 当前选中
    val currentSku = mutableMapOf<Long, Long>().apply {
      dataSet.forEach { option ->
        option.productOptionValues.forEach { optionValue ->
          if (optionValue.checked) {
            put(option.id, optionValue.id)
          }
        }
      }
    }
    Timber.v("currentSku = %s", currentSku)

    // 当前可选
    val option = dataSet[position]
    val values = option.productOptionValues.map { optionValue ->
      val sku = currentSku.toMutableMap()
      sku[option.id] = optionValue.id
      sku
    }
    Timber.v("values = %s", values)

    // 更新可选项
    values.forEachIndexed { index, mutableMap ->
      option.productOptionValues[index].enabled = allSkus.find { sku -> sku.entries.containsAll(mutableMap.entries) } != null
    }

    val enables = values.map {
      allSkus.find { sku -> sku.entries.containsAll(it.entries) } != null
    }
    Timber.v("enables = %s", enables)

    holder.bind(option)
  }

  fun submitList(list: List<ProductDetail.Option>, skus: List<ProductDetail.Sku>) {
    this.dataSet = list
    this.skus = skus
    notifyDataSetChanged()
  }
}